<%@page language="java" import="java.sql.*" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename="messages.recorrido"/>
<%
Integer userId=(Integer)request.getSession(false).getAttribute("id");
dbBean.DBConnectionManager connMgr=(dbBean.DBConnectionManager)application.getAttribute("connMgr");
if((userId==null) || (connMgr==null)) {
  application.log("- No existe una sesion de usuario o no se ha podido obtener una conexion con la BBDD");
%>
<html>
  <body onLoad="parent.location.href='/';">
  </body>
</html>
<%
} else {
String desde=(String)request.getParameter("desde");
String hasta=(String)request.getParameter("hasta");

if(desde==null)
        desde="";
if(hasta==null)
        hasta="";
Timestamp desdeTs=new Timestamp(0);
Timestamp hastaTs=new Timestamp(new java.util.Date().getTime());

if(desde!="") {
  try {
    desdeTs=Timestamp.valueOf(desde);
  } catch(IllegalArgumentException e) {e.printStackTrace();}
}
if(hasta!="") {
  try {
    hastaTs=Timestamp.valueOf(hasta);
  } catch(IllegalArgumentException e) {e.printStackTrace();}
}

Connection con=null;
StringBuffer datos=new StringBuffer();
 try {
  Timestamp timestamp=null;
  application.log("- Se va a consultar la ruta en la BBDD");
  con = connMgr.getConnection("mysql");
  PreparedStatement pstmt=null;
  if((desde=="") && (hasta=="")) {
      pstmt = con.prepareStatement("SELECT timestamp, latitud, longitud, velocidad, rumbo, altitud FROM datos WHERE UserId="+userId.toString()+" ORDER BY timestamp;");
  } else {
      pstmt = con.prepareStatement("SELECT timestamp, latitud, longitud, velocidad, rumbo, altitud FROM datos WHERE UserId="+userId.toString()+" AND timestamp BETWEEN ? AND ? ORDER BY timestamp;");
      pstmt.setTimestamp(1, desdeTs);
      pstmt.setTimestamp(2, hastaTs);
  }
  ResultSet rs=pstmt.executeQuery();
  while(rs.next()) {
      datos.append("#");
      timestamp=rs.getTimestamp(1);
      datos.append(timestamp.toString());
      datos.append(";");
      datos.append(rs.getString(2));
      datos.append(";");
      datos.append(rs.getString(3));
      datos.append(";");
      datos.append(rs.getString(4));
      datos.append(";");
      datos.append(rs.getString(5));
      datos.append(";");
      datos.append(rs.getString(6));
  }
  rs.close();
  pstmt.close();
  application.log("- Se ha obtenido la ruta correctamente");

} catch (SQLException e) {
  application.log("GoogleGPS_offline_descargar_GM.jsp",e);
}
if(con!=null)
  connMgr.freeConnection("mysql",con);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title>GPS-o&ugrave;</title>
<style type="text/css">
    v\:* {
      behavior:url(#default#VML);
    }
</style>

<style type="text/css">
    .posinfo    {
                width: 220px;
                font-family: arial, sans-serif;
                color: #0000A0;
                font-size: 75%;
                font-stretch: narrower;
                font-weight: bold;
                text-align: left;
                }
</style>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=" type="text/javascript" charset="utf-8"></script>
<script src="http://www.gpsou.es/GoogleGPS/scripts/markermanager.js"text/javascript" charset="utf-8"></script>
<script src="http://www.gpsou.es/GoogleGPS/scripts/pano_layer.js"text/javascript" charset="utf-8"></script>
<script src="http://www.gpsou.es/GoogleGPS/scripts/pano_maptypecontrol.js"text/javascript" charset="utf-8"></script>

<script  type="text/javascript">
//<![CDATA[

var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(8,8);
baseIcon.iconAnchor=new GPoint(4,4);
baseIcon.infoWindowAnchor=new GPoint(4,0);
var redIcon = (new GIcon(baseIcon, "http://www.gpsou.es/VEGPS/html/images/redSquare.png", null, ""));
var markerCurrent=new GMarker(new GLatLng(0, 0), redIcon);
var timer=setTimeout("", 0);
var posMarkerCurrent;

var tramoMedio;

var map;
var gMarker;
var ruta;
var latitudes, longitudes;
var points = [];
var datos="<%=datos.toString()%>";

function parseDate(str) {
  var ts=str.split(" ");
  var d=ts[0].split("-");
  var h=ts[1].split(":");
  var s=h[2].split(".");

  var fecha=new Date(Date.UTC(d[0], d[1] - 1, d[2], h[0], h[1], s[0], s[1]));

  return(fecha);
}

function fillDatos() {
      var results=ruta[posMarkerCurrent].split(";");

      var fecha=parseDate(results[0]);
      var velocidad=Math.round(results[3] / 10);
      var altitud=results[5];

      document.getElementById("fecha").innerHTML=fecha.toLocaleDateString();
      document.getElementById("hora").innerHTML=fecha.toLocaleTimeString();
      document.getElementById("velocidad").innerHTML=velocidad + " km/h";
      document.getElementById("altitud").innerHTML=altitud + " m";
}

function checkPoint(point) {
        var posLat=point.lat();
        var posLng=point.lng();
        var minDst=360;
        var dst;

        var inicio=0;
        var fin=ruta.length-1;

        clearTimeout(timer);

        posMarkerCurrent=inicio;
        for(i=inicio;i<=fin;i++) {
                dst=Math.abs(latitudes[i] - posLat) + Math.abs(longitudes[i] - posLng);
                if(dst < minDst) {
                        minDst=dst;
                        posMarkerCurrent=i;
                }
        }

        map.removeOverlay(markerCurrent);
        markerCurrent=new GMarker(new GLatLng(latitudes[posMarkerCurrent], longitudes[posMarkerCurrent]), redIcon, {clickable: true});
        map.addOverlay(markerCurrent);

        timer=window.setTimeout("fillDatos();", 1000);
}

function load() {
    if (GBrowserIsCompatible()) {

	map = new GMap2(document.getElementById("map"));
	map.addMapType(G_SATELLITE_3D_MAP);
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(0, 0), 13);
	map.addControl(new PanoMapTypeControl());
        map.enableScrollWheelZoom();
        map.enableContinuousZoom();
	map.setMapType(G_HYBRID_MAP);

	ruta=datos.split("#");
	ruta.shift();
	tramoMedio=dibuja();
	map.addOverlay(tramoMedio);

	GEvent.addListener(map, "mousemove", checkPoint);
    }
}


function dibuja() {

    var point;
    var latitud, longitud, latitudNMEA, longitudNMEA;
    var grados;
    var polylineRuta;
    var results;

    try {
      latitudes = new Array(ruta.length);
      longitudes = new Array(ruta.length);

      for(i=0; i<ruta.length; i++) {
        results=ruta[i].split(";");

        latitudNMEA=results[1];
        longitudNMEA=results[2];


        grados=Math.floor(latitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        latitud=(latitudNMEA/1000000-grados)/0.6+grados;
        grados=Math.floor(longitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        longitud=(longitudNMEA/1000000-grados)/0.6+grados;

        latitudes[i]=latitud;
        longitudes[i]=longitud;

        point = new GLatLng(latitud, longitud);
        points.push(point);
      }

      gMarker=new GMarker(point, null);
      map.addOverlay(gMarker);

      map.panTo(new GLatLng(latitud, longitud));

      polylineRuta=new GPolyline(points, "#0000ff", 5, 0.5, {clickable: true});

      document.getElementById("label").innerHTML="<fmt:message key="distance.text"/> <b>"+Math.round(polylineRuta.getLength())/1000+" km<\/b>";

    } catch (err) {alert(err.description);}

    return(polylineRuta);
}

//]]>
</script>

</head>

<body onload="load()" onunload="GUnload()">
  <p style="text-align: center"><img src="http://www.gpsou.es/VEGPS/html/images/GPSou-logo-banner.png" alt="GPSo&ugrave;"></p>
  <div style="text-align: center">

  <table style="margin-left: auto; margin-right: auto">
  <tr><td><div id="map" style="width: 500px; height: 300px; margin-left: auto; margin-right: auto; border: thick groove #A0A0FF"></div>
  <label id="label"> </label>
  </td><td valign="top">
        <p>
        <fmt:message key="data.text"/> <img src="http://www.gpsou.es/VEGPS/html/images/redSquare.png" alt="cuadrado rojo">):
        <br>
        </p>
        <table>
        <tr><td><fmt:message key="data.date"/> </td><td class="posinfo"><span id="fecha" title="<fmt:message key="data.date.title"/>"> </span></td></tr>
        <tr><td><fmt:message key="data.time"/> </td><td class="posinfo"><span id="hora" title="<fmt:message key="data.time.title"/>"> </span></td></tr>
        <tr><td><fmt:message key="data.speed"/> </td><td class="posinfo"><span id="velocidad" title="<fmt:message key="data.speed.title"/>"> </span></td></tr>
        <tr><td><fmt:message key="data.altitude"/> </td><td class="posinfo"><span id="altitud" title="<fmt:message key="data.altitude.title"/>"></td></tr>
        </table>
  </td></tr>
  </table>

  <p>
    <img src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Strict" height="31" width="88">
  </p>
  </div>
</body>

</html>

<%
}
%>

